package com.apes.autoparts.masterdata.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.masterdata.model.EpcBrandType;
import com.apes.autoparts.masterdata.repository.EpcBrandTypeRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @ClassName EpcBrandTypeService
 * @Description TODO
 * @Author pengyb
 * @Date 2019/11/19 14:40
 * @Version 1.0
 **/
@Service("epcBrandTypeService")
public class EpcBrandTypeService extends DomainService {
    @Autowired
    private EpcBrandTypeRepository epcBrandTypeRepository;

    @Autowired
    private EpcMasterDataManager epcMasterDataManager;

    public EpcBrandType save(SimpleRequest request) {
        EpcBrandType brandType = conserve(request);
        EpcBrandType epcBrandType = epcBrandTypeRepository.save(brandType);
        //同步至新系统
        epcMasterDataManager.synEsb("epc.brand.type.sendSave", request.getJO());
        //同步至erp
        synBrandType(brandType, "S");
        return epcBrandType;
    }

    public EpcBrandType update(SimpleRequest request) {
        EpcBrandType brandType = conserve(request);
        //同步至新系统
        Object invoke = invoke("epc.brand.type.sendSave", request.getJO());
        JSONObject header = JSONObject.parseObject(invoke.toString()).getJSONObject("header");
        if (!"success".equals(header.get("code"))) throw new RuntimeException(header.getString("message"));
        //同步至erp
        synBrandType(brandType, "U");
        return epcBrandTypeRepository.save(brandType);
    }

    private EpcBrandType conserve(SimpleRequest request) {
        EpcBrandType brandType = request.getO(EpcBrandType.class);
        brandType.setCreatorName(this.getSession(request).getUserName());
        brandType.setEntryDate(new Date());
        brandType.setTime(DateUtil.format(brandType.getEntryDate(), "yyyyMMdd.hhmmss.SSS"));
        return brandType;
    }

    public String delete(SimpleRequest request) {
        EpcBrandType brandType = request.getO(EpcBrandType.class);
        epcBrandTypeRepository.delete(brandType.getId());
        return "删除成功";
    }

    public void synBrandType(EpcBrandType brandType, String sign) {
        String method = "S".equals(sign) ? "mdmPplxService.insert" : "mdmPplxService.update";
        String TS01 = brandType.getTime();
        if ("U".equals(sign)) {
            //更新操作先查询
            TS01 = epcMasterDataManager.getVersion("mdmPplxService.query", JSONObject.toJSONString(mapper("PPLXID", brandType.getId())));
        }
        Map mapper = mapper("PPLXID", brandType.getId(), "PPLXMC", brandType.getName(), "PYM", brandType.getPinYingMa(), "CZY", brandType.getCreatorName());
        epcMasterDataManager.synErp(method, mapper);
    }

}
